<!--
 * @Description: 第二十七章（自定义指令directive）
 * @Author: IA ia@kepro.space
 * @Date: 2025-02-19 21:04:31
-->
<template>
  <div>
    <h1>第二十七章（自定义指令directive）</h1>
    <div>
      <h2>vue指令说明</h2>
      <p>Vue中有v-if,v-for,v-bind，v-show,v-model 等等一系列方便快捷的指令</p>
      <p>Vue3指令的钩子函数</p>
      <ul>
        <li>created 元素初始化的时候</li>
        <li>beforeMount 指令绑定到元素后调用 只调用一次</li>
        <li>mounted 元素插入父级dom调用</li>
        <li>beforeUpdate 元素被更新之前调用</li>
        <li>update 这个周期方法被移除 改用updated</li>
        <li>beforeUnmount 在元素被移除前调用</li>
        <li>unmounted 指令被移除后调用 只调用一次</li>
      </ul>
    </div>
    <div>
      <p>基础</p>
      <div>
        <el-button type="primary" @click="flag = !flag">切换</el-button>
        <A1 v-if="flag" v-move="{ background: 'red' }"></A1>
        <A2 v-move="{ flag: flag }"></A2>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import type { Directive, DirectiveBinding } from 'vue'
import A1 from '@/components/27th/A1.vue'
import A2 from '@/components/27th/A2.vue'
let flag = ref<boolean>(true)

type Dir = {
  background: string
}

// 指令命名有规范，必须用v开头
// 每个钩子函数都可以接收到v-move传的值，用...三个点的方式解构
const vMove: Directive = {
  created(...args: Array<any>) {
    console.log(args[2].children, '======> created 元素初始化的时候')
    console.log(args[2].children, 'created 打印 args： ', args)
  },
  beforeMount(el: HTMLElement) {
    console.log(el.innerHTML, '======> beforeMount 指令绑定到元素后调用 只调用一次')
  },
  mounted(el: HTMLElement, dir: DirectiveBinding<Dir>) {
    console.log(el.innerHTML, '======> mounted 元素插入父级dom调用')
    console.log(el.innerHTML, 'mounted dir value: ', dir.value)
    console.log(el.innerHTML, 'mounted dir value background: ', dir.value?.background)
    el.style.backgroundColor = dir.value?.background
  },
  beforeUpdate(el: HTMLElement) {
    console.log(el.innerHTML, '======> beforeUpdate 元素被更新之前调用')
  },
  updated(el: HTMLElement) {
    console.log(el.innerHTML, '======> update 这个周期方法被移除 改用 updated')
  },
  beforeUnmount(el: HTMLElement) {
    console.log(el.innerHTML, '======> beforeUnmount 在元素被移除前调用')
  },
  unmounted(el: HTMLElement) {
    console.log(el.innerHTML, '======> unmounted 指令被移除后调用 只调用一次')
  },
}
</script>
<style scoped>
h1,
h2,
h3,
hr {
  margin: 10px 0;
}

ul li {
  list-style: disc outside none;
}
</style>
